<!-- 接单 -->
<template>
	<view class="page">
		<!-- 头部 -->
		<view class="header">
			<view class="header-content">
				<view class="header-left" @click="goBack">
					<van-icon name="todo-list" size="25" color="#3B92F8" />
				</view>
				<text class="title">确认接单</text>
				<view class="header-right"></view>
			</view>
		</view>

		<!-- 主要内容 -->
		<view class="content">
			<!-- 订单信息卡片 -->
			<view class="card">
				<view class="card-header">
					<view class="info-icon">
						<van-icon name="completed-o" size="25" color="#3B92F8" />
					</view>
					<view class="card-title-wrapper">
						<text class="card-title">{{ orderData.title }}</text>
						<text class="card-subtitle">请确认以下培训信息</text>
					</view>
				</view>

				<view class="card-details">
					<view class="detail-item">
						<view class="detail-label">
							
							<van-icon name="clock-o"  size = "20" color="#3B92F8"/>
							<text class="label-text">培训时间</text>
						</view>
						<text class="detail-value">{{ formatTime(orderData.starttime) }} 
							{{ formatTime(orderData.endtime) }}</text>
					</view>

					<view class="detail-item">
						<view class="detail-label">
							<van-icon name="flag-o" size = "25" color="#3B92F8"/>
							<text class="label-text">培训地点</text>
						</view>
						<text class="detail-value">{{ orderData.location }}</text>
					</view>

					<view class="detail-item">
						<view class="detail-label">
							<van-icon name="orders-o"  size = "25" color="#3B92F8"/>
							<text class="label-text">材料要求</text>
						</view>
						<text class="detail-value">{{ orderData.requirements }}</text>
					</view>
				</view>
			</view>

			<!-- 上传区域 -->

			<!-- 上传区域 -->
			<view class="card">
				<text class="section-title">上传资料</text><span style="font-size: 24rpx; color: #333;">请上传一份您的个人简介，包括但不限于过往咨询经验，培训经验及海外项目类经验</span>

				<view class="upload-area" @click="chooseFile" @touchmove.stop.prevent>
					<input type="file" id="fileInput" class="file-input" multiple @change="handleFiles"
						accept=".ppt,.pptx,.pdf">
					<view class="upload-icon">
						<van-icon name="upgrade" size = "55" color="#10c303" />
					</view>
					<text class="upload-text">点击上传或拖放文件至此</text>
					<text class="upload-hint">支持PPT、PDF、pptx、xlsx格式，单个文件不超过50MB</text>
				</view>

				<!-- 修改后的文件列表部分 -->
				<view class="file-list" v-if="files && files.length > 0">
					<view v-for="(file, index) in files" :key="index" class="file-item">
						<view class="file-info">
							<text class="file-icon" :class="{'icon-pdf': isPDF(file), 'icon-ppt': !isPDF(file)}"></text>
							<view class="file-meta">
								<text class="file-name">{{ file.name || '未命名文件' }}</text>
								<text class="file-size">{{ formatFileSize(file.size || 0) }}</text>
							</view>
						</view>
						<view class="file-remove" @click.stop="removeFile(index)">
							<text class="" style="font-size: 60rpx;">×</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 备注区域 -->
			<view class="card">
				<text class="section-title">备注</text>
				<textarea class="remarks-input" v-model="remarks" placeholder="请输入备注信息（选填）" maxlength="200"></textarea>
				<view class="char-count">
					<text>{{ remarks.length }}/200</text>
				</view>
			</view>

			<!-- 提交按钮 -->
			<button class="submit-btn" @click="submitOrder" :disabled="submitting">
				<text v-if="!submitting">确认接单</text>
				<text v-else class="loading-icon">&#xe6a9;</text>
				<text v-if="submitting">提交中...</text>
			</button>
		</view>

		<!-- 底部信息 -->
		<view class="footer">
			<text class="footer-text">专业教学服务平台</text>
		</view>
	</view>
</template>

<script>
	import {
		fileUpload,
		confirmOrder
	} from "../../utils/getDate.js"
	export default {
		data() {
			return {
				orderData: {},
				files: [], // 确保已初始化
				remarks: '',
				submitting: false
			};
		},
		onLoad(options) {
			// 获取传递的订单数据
			if (options.order) {
				this.orderData = JSON.parse(decodeURIComponent(options.order));
			}
			console.log(this.orderData)
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},

			// 格式化时间
			formatTime(timeStr) {
				if (!timeStr) return '';
				return timeStr.replace(/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}):\d{2}/, '$1 $2');
			},

			// 选择文件
			chooseFile() {
				uni.chooseMessageFile({
					count: 9,
					type: 'all',
					success: (res) => {
						this.handleFiles(res.tempFiles);
					}
				});
			},
			// 处理文件
			handleFiles(tempFiles) {
				const validFiles = tempFiles.filter(file => {
					const validTypes = ['application/pdf', 'application/vnd.ms-powerpoint'];
					return validTypes.includes(file.type) ||
						file.name.endsWith('.pdf') ||
						file.name.endsWith('.ppt') ||
						file.name.endsWith('.pptx') ||
						file.name.endsWith('.xlsx');
				});
				if (validFiles.length !== tempFiles.length) {
					uni.showToast({
						title: '仅支持PPT和PDF格式文件',
						icon: 'none'
					});
				}
				this.files = [...this.files, ...validFiles];
			},



			// 获取文件图标
			getFileIcon(file) {
				if (!file) return 'icon-ppt';
				const name = file.name || '';
				const type = file.type || '';

				if (type.includes('pdf') || name.toLowerCase().endsWith('.pdf')) {
					return 'icon-pdf';
				}
				return 'icon-ppt';
			},

			// 新增判断PDF文件的方法
			isPDF(file) {
				if (!file) return false;
				const name = file.name || '';
				const type = file.type || '';
				return type.includes('pdf') || name.toLowerCase().endsWith('.pdf');
			},

			formatFileSize(size) {
				if (!size) return '0 MB';
				return (size / 1024 / 1024).toFixed(2) + ' MB';
			},

			removeFile(index) {
				if (this.files && this.files.length > index) {
					this.files.splice(index, 1);
				}
			},
			// 提交订单
			// 修改后的 submitOrder 方法
			async submitOrder() {
				if (this.files.length === 0) {
					uni.showToast({
						title: '请至少上传一个课程文件',
						icon: 'none'
					});
					return;
				}

				try {
					this.submitting = true;

					// 先上传文件
					const uploadResults = await this.uploadFiles();

					// 然后确认订单
					const confirmData = {
						orderId: this.orderData.orderId,
						note: this.remarks,
						uploadFile: uploadResults // 上传结果数组
					};

					const confirmRes = await confirmOrder(confirmData);

					if (confirmRes.state === 'ok') {
						uni.showToast({
							title: '接单申请已提交！',
							icon: 'success'
						});

						setTimeout(() => {
							uni.navigateBack()
						}, 1500);
					} else {
						throw new Error(confirmRes.message || '提交订单失败');
					}
				} catch (error) {
					console.error('提交失败:', error);
					uni.showToast({
						title: '提交失败: ' + (error.message || '请重试'),
						icon: 'none'
					});
				} finally {
					this.submitting = false;
				}
			},

			// 新增的上传文件方法
			async uploadFiles() {
				const uploadResults = [];

				for (const file of this.files) {
					try {
						const result = await new Promise((resolve, reject) => {
							uni.uploadFile({
								// url: 'https://applet.eapchina.net/api/educationalTeacher/fileUpload',
								url: 'http://192.168.1.128:8080/applet/api/educationalTeacher/fileUpload',
								filePath: file.path || file.url, // 文件路径
								name: 'fail', // 参数名
								formData: {}, // 可以添加其他表单数据
								success: (uploadRes) => {
									try {
										const data = JSON.parse(uploadRes.data);
										if (data && data.state === 'ok') {
											resolve(data.imgUrl); // 返回服务器返回的文件地址
										} else {
											reject(new Error(data.message || '文件上传失败'));
										}
									} catch (e) {
										reject(new Error('解析服务器响应失败'));
									}
								},
								fail: (error) => {
									reject(new Error(error.errMsg || '上传请求失败'));
								}
							});
						});

						uploadResults.push(result);
					} catch (error) {
						console.error('上传文件失败:', error);
						throw new Error(`文件 ${file.name} 上传失败: ${error.message}`);
					}
				}

				return uploadResults;
			}
		}
	};
</script>

<style>
	/* 基础样式 */
	.page {
		background-color: #f8fafc;
		color: #1e293b;
		font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Arial, sans-serif;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}

	/* 头部样式 */
	.header {
		background: white;
		padding: 15px;
		box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
		position: sticky;
		top: 0;
		z-index: 10;
		box-sizing: border-box;
	}

	.header-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.header-left,
	.header-right {
		width: 30px;
	}

	.title {
		font-size: 18px;
		font-weight: 600;
		color: #334155;
	}

	/* 内容区域 */
	.content {
		flex: 1;
		padding: 15px;
		box-sizing: border-box;
	}

	/* 卡片样式 */
	.card {
		background-color: white;
		border-radius: 12px;
		padding: 20px;
		box-sizing: border-box;
		margin-bottom: 15px;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
	}

	/* 卡片头部 */
	.card-header {
		display: flex;
		align-items: flex-start;
		margin-bottom: 16px;
	}

	.info-icon {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		background-color: #e0e7ff;
		color: #3b82f6;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 12px;
	}

	.card-title-wrapper {
		flex: 1;
	}

	.card-title {
		font-size: 18px;
		font-weight: 600;
		color: #334155;
		display: block;
	}

	.card-subtitle {
		font-size: 14px;
		color: #64748b;
		margin-top: 4px;
		display: block;
	}

	/* 卡片详情 */
	.card-details {
		padding-left: 52px;
		box-sizing: border-box;
	}

	.detail-item {
		margin-bottom: 16px;
	}

	.detail-label {
		display: flex;
		align-items: center;
		color: #64748b;
		margin-bottom: 4px;
	}

	.label-text {
		font-size: 14px;
		margin-left: 8px;
	}

	.detail-value {
		font-size: 16px;
		font-weight: 500;
		color: #1e293b;
	}

	/* 区块标题 */
	.section-title {
		font-size: 18px;
		font-weight: 600;
		color: #334155;
		display: block;
		margin-bottom: 16px;
	}

	/* 上传区域 */
	.upload-area {
		border: 2px dashed #cbd5e1;
		border-radius: 8px;
		padding: 30px 15px;
		box-sizing: border-box;
		text-align: center;
		margin-bottom: 15px;
	}

	.file-input {
		display: none;
	}

	.upload-icon {
		color: #3b82f6;
		margin-bottom: 12px;
	}

	.upload-icon .iconfont {
		font-size: 40px;
	}

	.upload-text {
		font-weight: 500;
		color: #334155;
		display: block;
		margin-bottom: 4px;
	}

	.upload-hint {
		font-size: 14px;
		color: #64748b;
	}

	/* 文件列表 */
	.file-list {
		max-height: 240px;
		overflow-y: auto;
	}

	.file-item {
		border-left: 3px solid #3b82f6;
		background-color: #f8fafc;
		border-radius: 6px;
		padding: 12px;
		box-sizing: border-box;
		margin-bottom: 8px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.file-info {
		display: flex;
		align-items: center;
		flex: 1;
		overflow: hidden;
	}

	.file-icon {
		margin-right: 12px;
		font-size: 20px;
	}

	.icon-pdf {
		color: #ef4444;
	}

	.icon-ppt {
		color: #3b82f6;
	}

	.file-meta {
		overflow: hidden;
	}

	.file-name {
		font-size: 16px;
		font-weight: 500;
		color: #1e293b;
		display: block;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.file-size {
		font-size: 12px;
		color: #64748b;
		display: block;
	}

	.file-remove {
		color: #94a3b8;
		padding: 4px;
		box-sizing: border-box;
	}

	.file-remove:active {
		color: #64748b;
	}

	/* 备注区域 */
	.remarks-input {
		width: 100%;
		border: 1px solid #e2e8f0;
		border-radius: 8px;
		padding: 12px;
		box-sizing: border-box;
		min-height: 100px;
		font-size: 16px;
	}

	.char-count {
		text-align: right;
		color: #94a3b8;
		font-size: 14px;
		margin-top: 4px;
	}

	/* 提交按钮 */
	.submit-btn {
		background-color: #3b82f6;
		color: white;
		font-weight: 600;
		padding: 12px;
		box-sizing: border-box;
		border-radius: 12px;
		margin-top: 15px;
		width: 100%;
		font-size: 16px;
		border: none;
	}

	.submit-btn:disabled {
		background-color: #cbd5e1;
	}

	.loading-icon {
		display: inline-block;
		animation: spin 1s linear infinite;
		margin-right: 8px;
	}

	@keyframes spin {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	/* 底部样式 */
	.footer {
		text-align: center;
		padding: 15px;
		box-sizing: border-box;
	}

	.footer-text {
		color: #94a3b8;
		font-size: 14px;
	}

	/* 图标字体 */
	.iconfont {
		font-family: "iconfont" !important;
		font-size: 16px;
		font-style: normal;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
	}
</style>